home *** CD-ROM | disk | FTP | other *** search
/ Megaware 1 / Megaware Volume 1.iso / programg / c-tutor / chap05.txt < prev    next >
Text File  |  1990-07-20  |  41KB  |  885 lines

  1.  
  2.  
  3.  
  4.                                                         Chapter 5
  5.                                                     ENCAPSULATION
  6.  
  7. As mentioned in Chapter 1, object oriented programming will seem
  8. very unnatural to a programmer with a lot of procedural programming
  9. experience.  This chapter is the beginning of the definition of
  10. object oriented programming, and we will study the topic of
  11. encapsulation which is a "divide and conquer" technique.  As we
  12. stated earlier, there are a lot of new terms used with object
  13. oriented programming.  Don't be intimidated by the new terminology,
  14. we will study the terms one at a time in a meaningful order.
  15.  
  16. Encapsulation is the process of forming objects which we will
  17. discuss throughout this chapter.  An encapsulated object is often
  18. called an abstract data type and it is what object oriented
  19. programming is all about.  Without encapsulation, which involves
  20. the use of one or more classes, there is no object oriented
  21. programming.  Of course there are other topics concerning object
  22. oriented programming, but this is the cornerstone.
  23.  
  24.  
  25. NO INFORMATION HIDING
  26. _________________________________________________________________
  27.  
  28. The program named OPEN.CPP is a really stupid      ==============
  29. program because it does next to nothing but it        OPEN.CPP
  30. will be the beginning point for our discussion     ==============
  31. of encapsulation, otherwise known as information
  32. hiding.  Information hiding is an important part
  33. of object oriented programming and you should have a good grasp of
  34. what it is and what it will do for you by the time we finish this
  35. chapter.
  36.  
  37. A very simple structure is defined in lines 4 through 6 which
  38. contains only a single int type variable within the structure. 
  39. This is sort of a silly thing to do but it will illustrate the
  40. problem we wish to overcome in this chapter.  Three variables are
  41. declared in line 10, each of which contains a single int type
  42. variable and each of the three variables are available anywhere
  43. within the main function.  Each variable can be assigned,
  44. incremented, read, modified, or have any number of operations
  45. performed on it.  A few of the operations are illustrated in lines
  46. 13 through 21 and should be self explanatory to anyone with a
  47. little experience with the C programming language.
  48.  
  49. An isolated local variable named piggy is declared and used in the
  50. same section of code to illustrate that there is nothing magic
  51. about this code.
  52.  
  53. Study this simple program carefully because it is the basis for
  54. beginning our study of encapsulation.  Be sure to compile and
  55. execute this program, then we will go on to the next example
  56. program.
  57.  
  58.                                                          Page 5-1
  59.  
  60.                                         Chapter 5 - Encapsulation
  61.  
  62. INFORMATION HIDING
  63. _________________________________________________________________
  64.  
  65. Examine the program named CLAS.CPP for our first   ==============
  66. example of a program with a little information        CLAS.CPP
  67. hiding contained in it.  This program is           ==============
  68. identical to the last one except for the way it
  69. does a few of its operations.  We will take the
  70. differences one at a time and explain what is happening here.  Keep
  71. in mind that this is a trivial program and the safeguards built
  72. into it are not needed for such a simple program but are used here
  73. to illustrate how to use these techniques in a larger much more
  74. complicated program.
  75.  
  76. The first difference is that we have a class instead of a structure
  77. beginning in line 4 of this program.  The only difference between
  78. a class and a structure is that a class begins with a private
  79. section whereas a structure has no private section automatically
  80. defined.  Everything in a structure is defaulted to public by
  81. definition of the C++ language, but you can declare a private
  82. section in a structure if you so desire.  The keyword class is used
  83. to declare a class as illustrated here.
  84.  
  85.  
  86. WHAT IS A PRIVATE SECTION?
  87. _________________________________________________________________
  88.  
  89. A private section of a class is a section of data which cannot be
  90. accessed outside of the class, it is hidden from any outside
  91. access.  Thus, the variable named data_store which is a part of the
  92. object (an object will be defined completely later) named dog1
  93. declared in line 23 is not available for use anywhere in the main
  94. program.  It seems a little dumb to declare a variable in the main
  95. program that we cannot use, but that is exactly what we did.
  96.  
  97. The class is composed of the single variable named data_store and
  98. two functions, one named set() and the other named get_value(). 
  99. A more complete definition of a class is a group of variables and
  100. one or more functions that can operate on that data.  Stay with us,
  101. we will tie this all together in a meaningful and useful way very
  102. soon.
  103.  
  104.  
  105. WHAT IS A PUBLIC SECTION?
  106. _________________________________________________________________
  107.  
  108. A new keyword, public, is introduced in line 6 which states that
  109. anything following this keyword can be accessed from the main
  110. program or any function that is within the scope of an object of
  111. the given class.  Because the two functions are defined following
  112. the keyword public, they are both public and available for use in
  113. the calling function or any other function that is within the scope
  114. of the calling function.  You should keep in mind that the private
  115. variable is not available to the calling program.  Thus, we can
  116.  
  117.                                                          Page 5-2
  118.  
  119.                                         Chapter 5 - Encapsulation
  120.  
  121. only use the variable by calling one of the two functions defined
  122. as a part of the class.  These are called member functions because
  123. they are members of the class.
  124.  
  125. Since we have declared two functions, we need to define them, by
  126. saying what each function will actually do.  This is done in lines
  127. 11 through 19 where they are each defined in the normal way except
  128. that the class name is prepended onto the function name and
  129. separated from it by a double colon.  These two function
  130. definitions are called the implementation of the functions.  The
  131. class name is required because we can use the same function name
  132. in other classes and the compiler must know with which class to
  133. associate each function implementation.
  134.  
  135. One of the key points to be made here is that the private data
  136. contained within the class is available within the implementation
  137. of the member functions of the class for modification or reading
  138. in the normal manner.  You can do anything with the private data
  139. within the function implementations which are a part of that class,
  140. but the private data of other classes is hidden and not available
  141. within the member functions of this class.  This is the reason we
  142. must prepend the class name to the function names of this class
  143. when defining them.
  144.  
  145.  
  146. In C++ we have three scopes of variables, local, file and class. 
  147. Local variables are localized to a single function and file
  148. variables are available anywhere in a file following their
  149. definition.  A variable with class scope is available anywhere
  150. within the scope of a class and nowhere else.
  151.  
  152. It would be well to mention at this point that it is legal to
  153. include variables and functions in the private part and additional
  154. variables and functions in the public part.  In most practical
  155. situations, variables are included in only the private part and
  156. functions are included in only the public part of a class
  157. definition.  Occasionally, variables or functions are used in the
  158. other part.  This sometimes leads to a very practical solution to
  159. a particular problem, but in general, the entities are used only
  160. in the places mentioned.
  161.  
  162.  
  163. MORE NEW TERMINOLOGY
  164. _________________________________________________________________
  165.  
  166. If we are going to learn how to effectively use object oriented
  167. programming, we must learn the new terminology of the technique,
  168. so we will list a few of them here and begin using them in the text
  169. to get you used to seeing and using them.
  170.  
  171.       A class is a grouping of data and methods.  A class is
  172.       very much like a type as used in ANSI-C, it is only a
  173.       pattern to be used to create a variable which can be
  174.       manipulated in a program.
  175.  
  176.                                                          Page 5-3
  177.  
  178.                                         Chapter 5 - Encapsulation
  179.  
  180.  
  181.       An object is an instance of a class.  An object is what
  182.       you actually use in a program since it has values and can
  183.       be changed.
  184.  
  185.       A method is a function contained within the class.  You
  186.       will find the functions used within a class referred to
  187.       as a method.
  188.  
  189.       A message is the same thing as a function call.  In
  190.       object oriented programming, we send messages instead of
  191.       calling functions.  For the time being, you can think of
  192.       them as identical.  Later in this tutorial we will see
  193.       that they are in fact slightly different.
  194.  
  195. With all the new terminology, we will continue our study of the
  196. program named CLAS.CPP and show you how to use the class.  We can
  197. now say that we have a class composed of one variable and two
  198. methods.  The methods operate on the variable contained in the
  199. class when they receive messages to do so.  In this tutorial we
  200. will use the terms object and variable interchangeably because both
  201. names are very descriptive of what the object really is.
  202.  
  203. This is a small point but it could be easily overlooked.  Lines 7
  204. and 8 of this program are actually the prototypes for the two
  205. methods, and is our first example of the use of a prototype within
  206. a class.  This is the reason we spent so much time on prototypes
  207. in the last chapter.  You will notice line 7 which says that the
  208. method named set requires one parameter of type int and returns
  209. nothing, hence the return type is void.  The method named
  210. get_value() however, according to line 8, has no input parameters
  211. but returns an int type value to the caller.
  212.  
  213.  
  214. SENDING A MESSAGE
  215. _________________________________________________________________
  216.  
  217. Following all of the definitions in lines 1 through 19, we finally
  218. come to the program where we actually use the class.  In line 23
  219. we declare three objects of the class one_datum and name the
  220. objects dog1, dog2, and dog3.  Each object contains a single data
  221. point which we can set through use of one method or read its value
  222. through use of the other method.  In line 26, we send a message to
  223. the object named dog1 instructing it to set its internal value to
  224. 12, and even though this looks like a function call, it is properly
  225. called sending a message to a method.  Remember that the object
  226. named dog1 has a method associated with it called set() that sets
  227. its internal value to the actual parameter included within the
  228. message.  You will notice that the form is very much like the means
  229. of accessing the elements of a structure.  You mention the name of
  230. the object with a dot connecting it to the name of the method.  In
  231. a similar manner, we send a message to each of the other two
  232. objects dog2 and dog3 to set their values to those indicated.
  233.  
  234.                                                          Page 5-4
  235.  
  236.                                         Chapter 5 - Encapsulation
  237.  
  238. Lines 31 and 32 have been commented out because the operations are
  239. illegal since the variable named data_store is private and not
  240. available to the code outside of the object itself.  It should be
  241. obvious, but it will be pointed out that the data contained within
  242. the object named dog1 is not available within the methods of dog2
  243. or dog3 because they are different objects.  These rules are all
  244. devised to help you develop better code more quickly and you will
  245. soon see how they help.
  246.  
  247. The other method defined for each object is used in lines 34
  248. through 36 to illustrate how it can be used.  In each case, another
  249. message is sent to each object and the returned result is output
  250. to the monitor via the stream library.
  251.  
  252.  
  253.  
  254. USING A NORMAL VARIABLE
  255. _________________________________________________________________
  256.  
  257. There is another variable named piggy declared and used throughout
  258. this example program that illustrates that a normal variable can
  259. be intermixed with the objects and used in the normal manner.  The
  260. use of this variable should pose no problem to you, so after you
  261. understand the program, be sure to compile and execute it.  It
  262. would be a good exercise for you to remove the comments from lines
  263. 31 and 32 to see what kind of error message your compiler issues.
  264.  
  265. This program illustrates information hiding but it will not be
  266. clear to you that it really does anything worthwhile until we study
  267. the next two programs.  Be sure to compile and execute this program
  268. before continuing on to the next example program.
  269.  
  270.  
  271.  
  272. A PROGRAM WITH PROBLEMS
  273. _________________________________________________________________
  274.  
  275. Examine the program named OPENPOLE.CPP for an    ================
  276. example of a program with a few serious problems   OPENPOLE.CPP
  277. that will be overcome in the next example        ================
  278. program by using the principles of
  279. encapsulation.
  280.  
  281. We have two structures declared, one being a rectangle and the
  282. other being a pole.  The data fields should be self explanatory
  283. with the exception of the depth of the flagpole which is the depth
  284. it is buried in the ground, the overall length of the pole is
  285. therefore the sum of the length and the depth.
  286.  
  287. Based on your experience with ANSI-C, you should have no problem
  288. at all understanding exactly what the program is doing, but you may
  289. be a bit confused at the meaning of the result found in line 38
  290. where we multiply the height of the square with the width of the
  291. box.  This is perfectly legal to do in ANSI-C or C++, but the
  292.  
  293.                                                          Page 5-5
  294.  
  295.                                         Chapter 5 - Encapsulation
  296.  
  297. result has no earthly meaning because the data are for two
  298. different entities.  Likewise, the result calculated in line 40 is
  299. even sillier because the product of the height of the square and
  300. the depth of the flagpole has absolutely no meaning in any physical
  301. real world system we can think up.
  302.  
  303. Wouldn't it be neat if we had a way to prevent such stupid things
  304. from happening in a large production program.  If we had a good
  305. program that defined all of the things we can do with a square and
  306. another program that defined everything we could do with a pole,
  307. and if the data could be kept mutually exclusive, we could prevent
  308. these silly things from happening.
  309.  
  310. It should come as no real surprise to you that the next program
  311. will do just those things for us and do it in a very elegant way. 
  312. Before proceeding on to the next example program, you should
  313. compile and execute this one even though it displays some silly
  314. results.
  315.  
  316.  
  317.  
  318. OBJECTS PROTECT DATA
  319. _________________________________________________________________
  320.  
  321. Examine the program named CLASPOLE.CPP as an     ================
  322. example of data protection in a very simple        CLASPOLE.CPP
  323. program.                                         ================
  324.  
  325. In this program the rectangle is changed to a
  326. class with the same two variables which are now private, and two
  327. methods to handle the private data.  One method is used to
  328. initialize the values of the objects created and the other method
  329. to return the area of the object.  The two methods are defined in
  330. lines 12 through 21 in the manner described earlier in this
  331. chapter.  The pole is left as a structure to illustrate that the
  332. two can be used together and that C++ is truly an extension of
  333. ANSI-C.
  334.  
  335. In line 33 we declare two objects, once again named box and square,
  336. but this time we cannot assign values directly to their individual
  337. components because they are private elements of the class.  Lines
  338. 36 through 38 are commented out for that reason and the messages
  339. are sent to the objects in lines 40 and 41 to tell them to
  340. initialize themselves to the values input as parameters.  The
  341. flag_pole is initialized in the same manner as in the previous
  342. program.  Using the class in this way prevents us from making the
  343. silly calculations we did in the last program.  The compiler is now
  344. being used to prevent the erroneous calculations.  The end result
  345. is that the stupid calculations we did in the last program are not
  346. possible in this program so lines 50 through 53 have been commented
  347. out.  Once again, it is difficult to see the utility of this in
  348. such a simple program.  In a large program, using the compiler to
  349. enforce the rules can pay off in a big way.
  350.  
  351.  
  352.  
  353.                                                          Page 5-6
  354.  
  355.                                         Chapter 5 - Encapsulation
  356.  
  357. This is the abstract data type mentioned earlier in this chapter,
  358. a model with an allowable set of variables for data storage and a
  359. set of allowable operations that can be performed on that stored
  360. data.  The only operations that can be performed on the data are
  361. those defined by the methods which prevents many kinds of erroneous
  362. or silly operations.  Encapsulation and data hiding bind the data
  363. and procedures, or methods, tightly together and limit the scope
  364. and visibility of each.  Once again, we have the divide and conquer
  365. technique in which an object is separated from the rest of the code
  366. and carefully developed in complete isolation from it.  Only then
  367. is it integrated into the rest of the code with a few very simple
  368. interfaces.
  369.  
  370.  
  371.  
  372. HAVE YOU EVER USED THIS TECHNIQUE BEFORE?
  373. _________________________________________________________________
  374.  
  375. A good example of the use of this technique is in the file commands
  376. you have been using with ANSI-C.  The data in the file is only
  377. available through the predefined functions provided by your
  378. compiler writer.  You have no direct access to the actual data
  379. because it is impossible for you to address the actual data stored
  380. on the disk.  The data is therefore private data, as far as you are
  381. concerned, but the available functions are very much like methods
  382. in C++.  There are two aspects of this technique that really count
  383. when you are developing software.  First, you can get all of the
  384. data you really need from the file system because the interface is
  385. complete, but secondly, you cannot get any data that you do not
  386. need.  You are prevented from getting into the file handling system
  387. and accidentally corrupting some data stored within it.  You are
  388. also prevented from using the wrong data because the functions
  389. available demand a serial access to the data.
  390.  
  391. Another example is in the monitor and keyboard handling routines. 
  392. You are prevented from getting into the workings of them and either
  393. corrupting them accidentally, or on purpose if you have such a
  394. bent, but once again, you are provided with all of the data
  395. interfaces that you really need.
  396.  
  397.  
  398. Suppose you are developing a program to analyze some
  399. characteristics of flagpoles.  You would not wish to accidentally
  400. use some data referring to where the flagpole program was stored
  401. on your hard disk as the height of the flagpole, nor would you wish
  402. to use the cursor position as the flagpole thickness or color.  The
  403. fact that the data is hidden from you protects you from
  404. accidentally doing such a thing when you are working at midnight
  405. to try to meet a schedule.  Once again, this is referred to as
  406. information hiding and is one of the primary advantages of object
  407. oriented programming over other methods.  Based on the discussion
  408. given above you can see that object oriented programming is not
  409. really new, since it has been used in some degree for as long as
  410. computers have been popular.  The newest development, however, is
  411.  
  412.                                                          Page 5-7
  413.  
  414.                                         Chapter 5 - Encapsulation
  415.  
  416. in allowing the programmer to partition his programs in such a way
  417. that he too can practice information hiding and reduce the
  418. debugging time.
  419.  
  420.  
  421.  
  422. WHAT DOES THIS COST?
  423. _________________________________________________________________
  424.  
  425. It should be clear that this technique will cost you something in
  426. efficiency because every access to the elements of the object will
  427. require the time and inefficiency of a call to a function, or
  428. perhaps I should be more proper and refer to it as a method.  The
  429. time saved in building a large program, however, could easily be
  430. saved in debug time when it comes time to iron out the last few
  431. bugs.  This is because a program made up of objects that closely
  432. match the application are much easier to understand than a program
  433. that does not.
  434.  
  435. This is obviously such a small program that it is silly to try to
  436. see any gain with this technique.  In a real project however, it
  437. could be a great savings if one person developed all of the details
  438. of the rectangle, programmed it, and made it available to you to
  439. simply use.  This is exactly what has been done for you if you
  440. consider the video monitor an object.  There is a complete set of
  441. preprogrammed and debugged routines you can use to make the monitor
  442. do anything you wish it to do, all you have to do is study the
  443. interface to the routines and use them, expecting them to work. 
  444. As a silly example of protection, it is impossible for you to
  445. multiply the size of your monitor screen by the depth of the flag
  446. pole because that information is not available to you to use in a
  447. corruptible way.
  448.  
  449. After you understand some of the advantages of this style of
  450. programming, be sure to compile and execute this program.
  451.  
  452.  
  453.  
  454. CONSTRUCTORS AND DESTRUCTORS
  455. _________________________________________________________________
  456.  
  457. The file named CONSPOLE.CPP introduces           ================
  458. constructors and destructors and should be         CONSPOLE.CPP
  459. examined at this time.                           ================
  460.  
  461. This program is identical to the last program
  462. except that a constructor has been added as well as a destructor. 
  463. The constructor is declared in line 8 and defined in lines 14
  464. through 18.  The constructor is called automatically by the C++
  465. system when the object is declared and can therefore be of great
  466. help in preventing the use of an uninitialized variable.  When the
  467. object named box is declared in line 46, the constructor is called
  468. automatically by the system which sets the values of its height and
  469. width each to 6.  This is printed out for reference in lines 49 and
  470.  
  471.                                                          Page 5-8
  472.  
  473.                                         Chapter 5 - Encapsulation
  474.  
  475. 50.  Likewise, when the square is declared in line 46, the values
  476. of the height and the width of the square are each initialized to
  477. 6 when the constructor is called automatically.
  478.  
  479. A constructor is defined as having the same name as the class
  480. itself.  In this case both are named rectangle.  The constructor
  481. cannot have a return type associated with it since it is not
  482. permitted to have a user defined return type.  It actually has a
  483. predefined return type, a pointer to the object itself, but we will
  484. not be concerned about this until much later in this tutorial. 
  485. Even though both objects are assigned values by the constructor,
  486. they are initialized in lines 58 and 59 to new values and
  487. processing continues.  Since we have a constructor that does the
  488. initialization, we should probably rename the method named
  489. initialize() something else but it illustrates the concept involved
  490. here.
  491.  
  492. The destructor is very similar to the constructor except that it
  493. is called automatically when each of the objects goes out of scope. 
  494. You will recall that automatic variables have a limited lifetime
  495. since they cease to exist when the enclosing block in which they
  496. were declared is exited.  When an object is about to be
  497. automatically deallocated, its destructor, if one exists, is called
  498. automatically.  A destructor is characterized as having the same
  499. name as the class but with a tilde prepended to the class name. 
  500. A destructor has no return type.
  501.  
  502. A destructor is declared in line 11 and defined in lines 31 through
  503. 35.  In this case the destructor only assigns zeros to the
  504. variables prior to their being deallocated, so nothing is really
  505. accomplished.  The destructor is only included for illustration of
  506. how it is used.  If some blocks of memory were dynamically
  507. allocated within an object, a destructor should be used to
  508. deallocate them prior to losing the pointers to them.  This would
  509. return their memory to the free store for further use later in the
  510. program.
  511.  
  512. It is interesting to note that if a constructor is used for an
  513. object that is declared prior to the main program, otherwise known
  514. as globally, the constructor will actually be executed prior to the
  515. execution of the main program.  In like manner, if a destructor is
  516. defined for such a variable, it will execute following the
  517. completion of execution of the main program.  This will not
  518. adversely affect your programs, but it is interesting to make note
  519. of.
  520.  
  521.  
  522.  
  523. OBJECT PACKAGING
  524. _________________________________________________________________
  525.  
  526. Examine the file named BOXES1.CPP for an example of how not to
  527. package an object for universal use.  This packaging is actually
  528. fine for a very small program but is meant to illustrate to you
  529.  
  530.                                                          Page 5-9
  531.  
  532.                                         Chapter 5 - Encapsulation
  533.  
  534. how to split your program up into smaller more    ================
  535. manageable files when you are developing a large     BOXES1.CPP
  536. program or when you are part of a team            ================
  537. developing a large system.  The last three
  538. example programs in this chapter will illustrate
  539. the proper method of packaging a class.
  540.  
  541. This program is very similar to the last one with the pole
  542. structure dropped and the class named box.  The class is defined
  543. in lines 4 through 12, the implementation of the class is given in
  544. lines 15 through 34, and the use of the class is given in lines 37
  545. through 50.  With the explanation we gave about the last program,
  546. the diligent student should have no problem understanding this
  547. program in detail.
  548.  
  549.  
  550.  
  551. INLINE IMPLEMENTATION
  552. _________________________________________________________________
  553.  
  554. The method in line 10 contains the implementation for the method
  555. as a part of the declaration because it is very simple, and because
  556. it introduces another new topic which you will use often in C++
  557. programming.  When the implementation is included in the
  558. declaration, it will be assembled inline wherever this function is
  559. called leading to much faster code.  This is because there is no
  560. overhead to accomplish the call to the method.  In some cases this
  561. will lead to code that is both smaller and faster.  This is yet
  562. another illustration of the efficiency built into the C++
  563. programming language.
  564.  
  565. Compile and execute this program in preparation for our study of
  566. the next three examples which are a repeat of this program in a
  567. slightly different form.
  568.  
  569.  
  570.  
  571. THE CLASS HEADER FILE
  572. _________________________________________________________________
  573.  
  574. If you examine BOX.HPP carefully, you will see    ===============
  575. that it is only the class definition.  No             BOX.HPP
  576. details are given of how the various methods are  ===============
  577. implemented except of course for the inline
  578. method named get_area().  This gives the
  579. complete definition of how to use the class with no implementation
  580. details.  You would be advised to keep a hardcopy of this file
  581. available as we study the next two files.  You will notice that it
  582. contains lines 4 through 12 of the previous example program named
  583. BOXES1.CPP.
  584.  
  585. This is called the class header file and cannot be compiled or
  586. executed.
  587.  
  588.  
  589.                                                         Page 5-10
  590.  
  591.                                         Chapter 5 - Encapsulation
  592.  
  593. THE CLASS IMPLEMENTATION FILE
  594. _________________________________________________________________
  595.  
  596. Examine the file named BOX.CPP for the            ===============
  597. implementation of the methods declared in the         BOX.CPP
  598. class header file.  Notice that the class header  ===============
  599. file is included into this file in line 2 which
  600. contains all of the prototypes for its methods. 
  601. The code from lines 15 through 34 of BOXES1.CPP is contained in
  602. this file which is the implementation of the methods declared in
  603. the class named box.
  604.  
  605. This file can be compiled but it cannot be executed because there
  606. is no main entry point which is required for all ANSI-C or C++
  607. programs.  When it is compiled, the object code will be stored in
  608. the current directory and available for use by other programs.  It
  609. should be noted here that the result of compilation is usually
  610. referred to as an object file because it contains object code. 
  611. This use of the word object has nothing to do with the word object
  612. as used in object oriented programming.  It is simply a matter of
  613. overloading the use of the word.  The practice of referring to the
  614. compiled result as a object file began long before the method of
  615. object oriented programming was ever considered.
  616.  
  617. The separation of the definition and the implementation is a major
  618. step forward in software engineering.  The definition file is all
  619. the user needs in order to use this class effectively in a program. 
  620. He needs no knowledge of the actual implementation of the methods. 
  621. If he had the implementation available, he may study the code and
  622. find a trick he could use to make the overall program slightly more
  623. efficient, but this would lead to nonportable software and possible
  624. bugs later if the implementor changed the implementation without
  625. changing the interface.  The purpose of object oriented programming
  626. is to hide the implementation in such a way that the implementation
  627. can not affect anything outside of its own small and well defined
  628. boundary or interface.
  629.  
  630. You should compile this program now and we will use the result with
  631. the next example program.
  632.  
  633.  
  634.  
  635. USING THE BOX OBJECT
  636. _________________________________________________________________
  637.  
  638. Examine the file named BOXES2.CPP and you will   ================
  639. find that the object we defined previously is       BOXES2.CPP
  640. used within this file.  In fact, these last      ================
  641. three programs taken together are identical to
  642. the program named BOXES1.CPP studied earlier.
  643.  
  644. The BOX.HPP file is included here, in line 3, since the definition
  645. of the box is needed to declare three objects and use their
  646. methods.  You should have no trouble seeing that this is a repeat
  647.  
  648.                                                         Page 5-11
  649.  
  650.                                         Chapter 5 - Encapsulation
  651.  
  652. of the previous program and will execute in exactly the same way. 
  653. There is a big difference in BOXES1.CPP and BOXES2.CPP as we will
  654. see shortly.
  655.  
  656. A very important distinction must be made at this point.  We are
  657. not merely calling functions and changing the terminology a little
  658. to say we are sending messages.  There is an inherent difference
  659. in the two operations.  Since the data for each object is tightly
  660. bound up in the object, there is no way to get to the data except
  661. through the methods and we send a message to the object telling it
  662. to perform some operation based on its internally stored data. 
  663. However, whenever we call a function, we take along the data for
  664. it to work with as parameters since it doesn't contain its own
  665. data.
  666.  
  667. Be sure to compile and execute this program, but when you come to
  668. the link step, you will be required to link this program along with
  669. the result of the compilation when you compiled the class named
  670. box.  The file is probably named BOX.OBJ that must be linked with
  671. this file.  You may need to consult the documentation for your C++
  672. compiler to learn how to do this.  Even if it seems to be a lot of
  673. trouble to learn how to link several files together, it will be
  674. worth your time to do so now because we will be linking several
  675. more multifile C++ programs in the remainder of this tutorial.
  676.  
  677. If you are using TURBO C++, this is your first opportunity to use
  678. a project file.  If you are using Zortech C++, you can use the make
  679. facility included with your compiler.  Whichever one you are using,
  680. it would pay you to stop and learn how to use the multifile
  681. technique provided with your compiler because you will need to use
  682. it several times before the end of this tutorial.  The nature of
  683. C++ tends to drive the programmer to use many files for a given
  684. programming project and you should develop the habit early.
  685.  
  686.  
  687.  
  688. INFORMATION HIDING
  689. _________________________________________________________________
  690.  
  691. The last three example programs illustrate a method of information
  692. hiding that can have a significant impact on the quality of
  693. software developed for a large project.  Since the only information
  694. the user of the class really needs is the class header, that is all
  695. he needs to be given.  The details of implementation can be kept
  696. hidden from him to prevent him from studying the details and
  697. possibly using a quirk of programming to write some rather obtuse
  698. code.  Since he doesn't know exactly what the implementor did, he
  699. must follow only the definition given in the header file.  This can
  700. have a significant impact on a large project.  As mentioned
  701. earlier, accidental corruption of data is prevented also.
  702.  
  703. Another reason for hiding the implementation is economic.  The
  704. company that supplied you with your C++ compiler gave you many
  705. library functions but did not supply the source code to the library
  706.  
  707.                                                         Page 5-12
  708.  
  709.                                         Chapter 5 - Encapsulation
  710.  
  711. functions, only the interface to each function.  You know how to
  712. use the file access functions but you do not have the details of
  713. implementation, nor do you need them.  Likewise a class development
  714. industry can develop which supplies users with libraries of high
  715. quality, completely developed and tested classes, for a licensing
  716. fee of course.  Since the user only needs the interface defined,
  717. he can be supplied with the interface and the object (compiled)
  718. code for the object and can use it in any way he desires.  The
  719. suppliers source code is protected from accidental or intentional
  720. compromise and he can maintain complete control over it.
  721.  
  722. It is very important that you understand the principles covered in
  723. this chapter before proceeding on to the next chapter.  If you feel
  724. you are a little weak in any of the areas covered here, you should
  725. go over them again before proceeding on.  A point that should be
  726. made here that may be obvious to you, is that it requires some
  727. amount of forethought to effectively use classes.
  728.  
  729.  
  730.  
  731. ABSTRACT DATA TYPES
  732. _________________________________________________________________
  733.  
  734. We mentioned the abstract data type at the beginning of this
  735. chapter and again briefly midway through, and it is time to
  736. describe it a little more completely.  An abstract data type is a
  737. group of data, each of which can store a range of values, and a set
  738. of methods or functions that can operate on that data.  Since the
  739. data are protected from any outside influence, it is protected and
  740. said to be encapsulated.  Also, since the data is somehow related,
  741. it is a very coherent group of data that may be highly interactive
  742. with each other, but with no interaction with the outside world,
  743. it is completely decoupled from its surroundings.
  744.  
  745. The methods, on the other hand, are coupled to the outside world
  746. through the interface, but there are a limited number of contacts
  747. with the outside world and therefore a weak coupling with the
  748. outside.  The object is therefore said to be loosely coupled to the
  749. outside world.  Because of the tight coherency and the loose
  750. coupling, ease of maintenance of the software is greatly enhanced. 
  751. The ease of maintenance may be the greatest benefit of object
  752. oriented programming.
  753.  
  754. It may bother you that even though the programmer may not use the
  755. private variables directly outside of the class, they are in plain
  756. sight and he can see what they are and can probably make a good
  757. guess at exactly how the class is implemented.  The variables could
  758. have been hidden completely out of sight in another file, but
  759. because the designers of C++ wished to make the execution of the
  760. completed application as efficient as possible, the variables were
  761. left in the class definition where they can be seen but not used.
  762.  
  763.  
  764.  
  765.  
  766.                                                         Page 5-13
  767.  
  768.                                         Chapter 5 - Encapsulation
  769.  
  770. FRIEND FUNCTIONS
  771. _________________________________________________________________
  772.  
  773. A function outside of a class can be defined to be a friend
  774. function by the class which gives the friend free access to the
  775. private members of the class.  This in effect, opens a small hole
  776. in the protective shield of the class, so it should be used very
  777. carefully and sparingly.  There are cases where it helps to make
  778. a program much more understandable and allows controlled access to
  779. the data.  Friend functions will be illustrated in some of the
  780. example programs later in this tutorial.  It is mentioned here for
  781. completeness of this section.  A single function can be declared
  782. as a friend, as well as members of other classes, and even entire
  783. classes can be given friend status if needed in a program.  Neither
  784. a constructor nor a destructor can be a friend function.
  785.  
  786.  
  787. THE struct IN C++
  788. _________________________________________________________________
  789.  
  790. The struct is still useable in C++ and operates just like it does
  791. in ANSI-C with one addition.  You can include methods in a
  792. structure that operate on data in the same manner as in a class,
  793. but all methods and data are automatically defaulted to be public
  794. in a structure.  Of course you can make any of the data or methods
  795. private but only if you are using a C++ compiler that supports C++
  796. version 2.0 or higher.  Earlier versions of C++ did not permit a
  797. private section in a structure.  The structure should be used only
  798. for constructs that are truly structures.  If you are building even
  799. the simplest objects, use classes to define them.
  800.  
  801.  
  802. INITIALIZING THE class AND struct
  803. _________________________________________________________________
  804.  
  805. The struct can be initialized with an aggregate in exactly the same
  806. manner that a struct can be initialized in ANSI-C, but this is not
  807. permitted for a class.  The class is allowed to contain private
  808. members, so it cannot be initialized without access to the private
  809. members.  It could have been possible to allow aggregate
  810. initialization of classes without private members, but this would
  811. have greatly complicated the compiler while adding little to the
  812. capability since a class without a private member is contrary to
  813. the entire thrust of object oriented programming.  The designers
  814. of C++ chose therefore to prohibit aggregate initialization of
  815. class variables in order to simplify the job of the compiler
  816. writer.  This probably adds to the efficiency of the resulting
  817. applications.  This really is no limitation because both struct and
  818. class types can be initialized with constructors or initialization
  819. methods.
  820.  
  821. We will continue our discussion of encapsulation in the next
  822. chapter.
  823.  
  824.  
  825.                                                         Page 5-14
  826.  
  827.                                         Chapter 5 - Encapsulation
  828.  
  829.  
  830. PROGRAMMING EXERCISES
  831. _________________________________________________________________
  832.  
  833.  
  834. 1.   Add a method to CLAS.CPP which will supply the square of the
  835.      stored value.  Include some code in the main program to read
  836.      and display the squared values.
  837.  
  838. 2.   Continuing with CLAS.CPP, add a constructor to initialize the
  839.      stored value to 10 and add a few lines of code to the main
  840.      program to display the values immediately following the object
  841.      definition.
  842.  
  843. 3.   Add an output statement to the rectangle constructor of the
  844.      program named CONSPOLE.CPP and another to the destructor to
  845.      prove to yourself that they really are called by the system
  846.      when we said they are.
  847.  
  848.  
  849.  
  850.  
  851.  
  852.  
  853.  
  854.  
  855.  
  856.  
  857.  
  858.  
  859.  
  860.  
  861.  
  862.  
  863.  
  864.  
  865.  
  866.  
  867.  
  868.  
  869.  
  870.  
  871.  
  872.  
  873.  
  874.  
  875.  
  876.  
  877.  
  878.  
  879.  
  880.  
  881.  
  882.  
  883.  
  884.                                                         Page 5-15
  885.